#!/bin/bash

# You can run as 
# ./traff_meter.sh /usr/twm2 eth0 1
# or as if need use data from module.conf
# ./traff_meter.sh /usr/twm2 


VARIABLES=(`perl $TWMFOLDER/bin/get_varMultipleValue.pl ifconfig grep date gawk sha1sum _DEFAULT_`)
ifconfig=${VARIABLES[0]}
grep=${VARIABLES[1]}
date=${VARIABLES[2]}
gawk=${VARIABLES[3]}
sha1sum=${VARIABLES[4]}

while true
do
	logfolder="$TWMFOLDER/modules/if_meter/logs"
	checksumm=`$sha1sum $TWMFOLDER/modules/if_meter/module.conf | $gawk '{print \$1}'`


	interfaces="$2"
	if [ "$interfaces" = "" ]; then
		interfaces=`perl $TWMFOLDER/bin/get_varValue.pl interfaces if_meter | sed -e 's/,/ /g'`
	fi

	count_iteration="$3"
	LOGFILE="$4"
	if [ "$count_iteration" = "" ]; then
		count_iteration=`perl $TWMFOLDER/bin/get_varValue.pl period if_meter`
		LOGFILE="file"
	fi

	index=-1
	for interface in $interfaces; do
		index=`expr $index + 1`
		RX[$index]=0
		TX[$index]=0
		NRXS[$index]="0"
		NTXS[$index]="0"
	done

	while true
	do
		index=-1
		for interface in $interfaces; do
			index=`expr $index + 1`
			NRXS[$index]="0"
			NTXS[$index]="0"
			IS_IF_UP=`$ifconfig | $grep $interface | wc -l | sed -e 's/\s//g'`
			if [ "$IS_IF_UP" != "0" ]; then
				IS_IF_UP=`$ifconfig $interface | $grep $interface | wc -l | sed -e 's/\s//g'`
				if [ "$IS_IF_UP" = "1" ]; then
					NRX[$index]=`$ifconfig $interface | $grep "RX bytes" | cut -d ' ' -f 12 | cut -d ':' -f 2`
					NTX[$index]=`$ifconfig $interface | $grep "RX bytes" | cut -d ' ' -f 17 | cut -d ':' -f 2`
					if [ "${RX[$index]}" != "0" ]; then
						NRXS[$index]=`expr ${NRX[$index]} - ${RX[$index]}`
						NTXS[$index]=`expr ${NTX[$index]} - ${TX[$index]}`
					fi
					RX[$index]=${NRX[$index]}
					TX[$index]=${NTX[$index]}
				else
					echo "INTERFACE IS DOWN: $interface"
				fi
			fi

			if [ "${NRXS[$index]}" != "0" ] || [ "${NTXS[$index]}" != "0" ]; then
				if [ "$LOGFILE" = "file" ]; then
					echo `$date +%s`	"R: ${NRX[$index]} (+${NRXS[$index]})	T: ${NTX[$index]} (+${NTXS[$index]})" >> "$logfolder/"$interface"_"`$date +%Y`"_"`$date +%m`"_"`$date +%d`.log
#					echo $interface `$date +%s`	"R: ${NRX[$index]} (+${NRXS[$index]})	T: ${NTX[$index]} (+${NTXS[$index]})"
				else
					echo -ne \\r "$interface RX bytes: ${NRX[$index]} (+${NRXS[$index]})" "TX bytes: ${NTX[$index]} (+${NTXS[$index]})"
				fi
			fi
		done

		checksumm2=`$sha1sum $TWMFOLDER/modules/if_meter/module.conf | $gawk '{print \$1}'`
		if [ $checksumm != $checksumm2 ]; then
			break
		fi

		sleep $count_iteration
	done
done
